import express from "express";
import rateLimit from "express-rate-limit";
import { adminLogin, registerAdmin, adminLogout, getCaptcha, getLoginStatus } from "../controllers/adminController";
import { authenticate, authorize } from "../middleware/auth";
import { ArticleController } from "../controllers/articleController";
import { CategoryController } from "../controllers/categoryController";
import os from "os";
import process from "process";
import adminUserRoutes from "./adminUserRoutes";
import { getOssSignController } from "../controllers/ossController";

const router = express.Router();
const articleController = new ArticleController();
const categoryController = new CategoryController();

// 速率限制中间件
const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 10, // 每个IP在15分钟内最多10次请求
  standardHeaders: true,
  legacyHeaders: false,
  message: { success: false, message: "操作过于频繁，请15分钟后再试" },
});

// 开发环境跳过速率限制
const isDevelopment = process.env.NODE_ENV === 'development';
const conditionalAuthLimiter = isDevelopment ? (req: any, res: any, next: any) => next() : authLimiter;

// === 公开路由 (无需认证) ===
router.get("/captcha", getCaptcha);
router.get("/login-status", getLoginStatus);
router.post("/register", conditionalAuthLimiter, registerAdmin);
router.post("/login", conditionalAuthLimiter, adminLogin);
router.post("/logout", adminLogout);

// === 后端认证路由 (需要admin权限) ===

// --- 文章管理 ---
// 查询
router.get("/articles", authenticate, authorize(["admin", "editor"]), articleController.getArticles.bind(articleController));
router.get("/articles/stats", authenticate, authorize(["admin", "editor"]), articleController.getArticleStats.bind(articleController));
router.get("/articles/recommend", authenticate, authorize(["admin", "editor"]), articleController.getRecommendArticles.bind(articleController));
router.get("/articles/top", authenticate, authorize(["admin", "editor"]), articleController.getTopArticles.bind(articleController));
// 导出
router.get("/articles/export", authenticate, authorize(["admin", "editor"]), articleController.exportArticles.bind(articleController));
router.get("/articles/:id", authenticate, authorize(["admin", "editor"]), articleController.getArticleById.bind(articleController));
// 创建、更新、删除
router.post("/articles", authenticate, authorize(["admin", "editor"]), articleController.createArticle.bind(articleController));
router.put("/articles/:id", authenticate, authorize(["admin", "editor"]), articleController.updateArticle.bind(articleController));
router.delete("/articles/:id", authenticate, authorize(["admin", "editor"]), articleController.deleteArticle.bind(articleController));

// --- 分类管理 ---
// 查询
router.get("/categories", authenticate, authorize(["admin", "editor"]), categoryController.getAllCategories.bind(categoryController));
router.get("/categories/:id", authenticate, authorize(["admin", "editor"]), categoryController.getCategoryById.bind(categoryController));
// 创建、更新、删除
router.post("/categories", authenticate, authorize(["admin", "editor"]), categoryController.createCategory.bind(categoryController));
router.put("/categories/:id", authenticate, authorize(["admin", "editor"]), categoryController.updateCategory.bind(categoryController));
router.delete("/categories/:id", authenticate, authorize(["admin", "editor"]), categoryController.deleteCategory.bind(categoryController));

// --- OSS签名 ---
router.get("/oss/sign", authenticate, authorize(["admin", "editor"]), getOssSignController);

// --- 用户管理 ---
router.use("/users", adminUserRoutes);

// --- 仪表盘统计 ---
router.get("/dashboard/stats", authenticate, authorize(["admin"]), async (req, res) => {
  try {
    const { ArticleService } = await import("../services/articleService");
    const articleService = new ArticleService();
    const statsResult = await articleService.getArticleStats();

    res.json({
      success: true,
      data: {
        articles: statsResult.success
          ? statsResult.data
          : {
              total: 0,
              published: 0,
              draft: 0,
              top: 0,
              recommend: 0,
            },
      },
    });
  } catch (error) {
    console.error("获取统计数据失败:", error);
    res.status(500).json({
      success: false,
      error: "获取统计数据失败",
    });
  }
});

router.get("/server-status", (req, res) => {
  const cpus = os.cpus();
  res.json({
    success: true,
    data: {
      uptime: process.uptime(),
      platform: process.platform,
      arch: process.arch,
      nodeVersion: process.version,
      memory: {
        total: os.totalmem(),
        free: os.freemem(),
        used: os.totalmem() - os.freemem(),
      },
      cpu: {
        model: cpus[0]?.model || "",
        cores: cpus.length,
        speed: cpus[0]?.speed || 0,
      },
    },
  });
});

export default router;
